﻿var MB = window["MB"] || {}
MB.page = MB["page"] || {}
MB.page.workshop = (function () {
    var settings = {
        isWorkshopInited: false,
        isPipelineInited: false,
        workshop_grid: null,
        workshop_temp_id: 0,
        line_temp_id:0
    }
    var current_workshop = {
        WORKSHOP_CODE: '',
        WORKSHOP_NAME: ''
    }
    var col_model = {
        ws: ['WORKSHOP_NAME', 'WORKSHOP_CODE', 'NET_CAPACITY','WORKSHOP_STATUS_TEXT', 'UPDATE_TIME', 'UPDATE_USER'],
        ws_write: [1, 0, 0, 0, 0],
        pl: ['LINE_NAME', 'LINE_CODE'
            , 'CATEGORY', 'CAPACITY'
            , 'UPDATE_TIME', 'UPDATE_USER'],
        pl_write:[1,0,1,1,0,0,0,0]
    }

    var select_model = {
        ws: {
            ids: [],
            temp_ids:[]
        },
        pl: {
            ids: [],
            temp_ids:[]
        }
    }
    var initLine = function () {
        if (settings.isPipelineInited === false) settings.isPipelineInited = true
        else {
            $('#lineSearchForm').submit()
            return
        }
        $('#line_grid').dataTable().fnDestroy()
        $('#line_grid').dataTableExtention({
            "initLoadFormParams": true,
            "filterForm": "#lineSearchForm",
            "ordering": false,
            "paging": false,
            "sAjaxSource": "/Workshop/SearchPipeline",
            "aoColumns": [
            { "mDataProp": null },
            { "mDataProp": null },
            { "mDataProp": "LINE_NAME" },
            { "mDataProp": "LINE_CODE" },
            { "mDataProp": "CATEGORY" },
            { "mDataProp": "CAPACITY" },
            { "mDataProp": "UPDATE_TIME" },
            { "mDataProp": "UPDATE_USER" }
            ],
            "columnDefs": [{
                "orderable": false,
                "targets": [0],
                "render": function (data, type, row) {

                    return '<input '
                                + 'data-id="' + row.ID
                                + '" data-model="pl" '
                                + ' op-type="check" type="checkbox" class="checkbox" id="' + row.ID + '" />'

                }
            }, {
                "orderable": false,
                "targets": [1],
                "render": function (data, type, row) {
                    return '<a '
                                + 'data-id="' + row.ID
                                + '" data-model="pl" '
                                + ' op-type="active" type="text" class="btn btn-xs green">编辑</a>'
                }
            }, {
                "orderable": false,
                "targets": [2],
                "render": function (data, type, row) {
                    var name = col_model.pl[0]
                    var value = row[name]
                    var writeable = col_model.pl_write[0]
                    return '<input '
                             + ' data-id="' + row.ID
                        + '" data-model="pl" '
                        + ' data-name="' + name
                        + '" data-write="'+writeable+'" '
                        + ' value="' + value + '" type="text" readonly="readonly"/>'

                }
            }, {
                "orderable": false,
                "targets": [3],
                "render": function (data, type, row) {
                    var name = col_model.pl[1]
                    var value = row[name]
                    var writeable = col_model.pl_write[1]
                    return '<input '
                             + ' data-id="' + row.ID
                        + '" data-model="pl" '
                        + ' data-name="' + name
                        + '" data-write="'+writeable+'" '
                        + ' value="' + value + '" type="text" readonly="readonly"/>'

                }
            }, {
                "orderable": false,
                "targets": [4],
                "render": function (data, type, row) {
                    var name = col_model.pl[2]
                    var value = row[name]
                    var writeable = col_model.pl_write[2]
                    return '<input '
                             + ' data-id="' + row.ID
                        + '" data-model="pl" '
                        + ' data-name="' + name
                        + '" data-write="' + writeable + '" '
                        + ' value="' + value + '" type="text" readonly="readonly"/>'

                }
            }, {
                "orderable": false,
                "targets": [5],
                "render": function (data, type, row) {
                    var name = col_model.pl[3]
                    var value = row[name]
                    var writeable = col_model.pl_write[3]
                    return '<input '
                             + ' data-id="' + row.ID
                        + '" data-model="pl" '
                        + ' data-name="' + name
                        + '" data-write="'+writeable+'" '
                        + ' value="' + value + '" type="text" readonly="readonly"/>'

                }
            },
            {
                "orderable": false,
                "targets": [6],
                "render": function (data, type, row) {
                    var name = col_model.pl[4]
                    var value = getDate(row[name])
                    var writeable = col_model.pl_write[4]
                    return '<input '
                             + ' data-id="' + row.ID
                        + '" data-model="pl" '
                        + ' data-name="' + name
                        + '" data-write="' + writeable + '" '
                        + ' value="' + value + '" type="text" readonly="readonly"/>'

                }
            },
            {
                "orderable": false,
                "targets": [7],
                "render": function (data, type, row) {
                    var name = col_model.pl[5]
                    var value = row[name]
                    var writeable = col_model.pl_write[5]
                    return '<input '
                             + ' data-id="' + row.ID
                        + '" data-model="pl" '
                        + ' data-name="' + name
                        + '" data-write="' + writeable + '" '
                        + ' value="' + value + '" type="text" readonly="readonly"/>'

                }
            }
            ],
            "drawCallback": function () {
                if ($('input[data-type="item"]').length == $('input[data-type="item"][checked="checked"]').length) {
                    $('#selectAll').parent().addClass('checked')
                } else {
                    $('#selectAll').parent().removeClass('checked')
                }
            },
            "footerCallback": function (row, data, start, end, display) {
            }
        })
    }
    var initWorkShop = function () {
        if (settings.isWorkshopInited === false) settings.isWorkshopInited = true
        else {
            $('#workshopSearchForm').submit()
            return;
        }
        $('#workshop_grid').dataTable().fnDestroy()
        $('#workshop_grid').dataTableExtention({
            "initLoadFormParams": true,
            "filterForm": "#workshopSearchForm",
            "ordering": false,
            "paging":false,
            "sAjaxSource": "/Workshop/SearchWorkshop",
            "aoColumns": [
            { "mDataProp": null },
            { "mDataProp": null },
            { "mDataProp": "WORKSHOP_NAME" },
            { "mDataProp": "WORKSHOP_CODE" },
            { "mDataProp": "NET_CAPACITY" },
            { "mDataProp": "WORKSHOP_STATUS"},
            { "mDataProp": "UPDATE_TIME" },
            { "mDataProp": "UPDATE_USER" }
            ],
            "columnDefs": [{
                "orderable": false,
                "targets": [0],
                "render": function (data, type, row) {
                    if (row.PRODUCE_COUNT == 0) {
                        return '<input '
                               + 'data-id="' + row.ID
                               + '" data-model="ws" '
                               + ' op-type="check" type="checkbox" class="checkbox" id="' + row.ID + '" />'
                    }
                    return '<a href="javascript:void(0)" class="btn btn-xs red">排程锁定</a>'
                }
            }, {
                "orderable": false,
                "targets": [1],
                "render": function (data, type, row) {
                    return  '<a data-id="' + row.ID
                                + '" data-model="ws"'
                                + ' op-type="line" type="text" class="btn btn-xs green">编辑</a>'
                }
            }, {
                "orderable": false,
                "targets": [2],
                "render": function (data, type, row) {
                    var name = col_model.ws[0]
                    var value = row[name]
                    return '<input '
                             + ' data-id="' + row.ID
                        + '" data-model="ws" '
                        + ' data-name="' + name
                        + '" data-write="1" '
                        + ' value="' + value + '" type="text" readonly="readonly"/>'

                }
            }, {
                "orderable": false,
                "targets": [3],
                "render": function (data, type, row) {
                    var name = col_model.ws[1]
                    var value = row[name]
                    return '<input '
                             +' data-id="' + row.ID
                        + '" data-model="ws" '
                        + ' data-name="' + name
                        + '" data-write="0" '
                        + ' value="' + value + '" type="text" readonly="readonly"/>'

                }
            },{
                "orderable": false,
                "targets": [4],
                "render": function (data, type, row) {
                    var name = col_model.ws[2]
                    var value = row[name]
                    return '<input '
                             +' data-id="' + row.ID
                        + '" data-model="ws" '
                        + ' data-name="' + name
                        + '" data-write="0" '
                        + ' value="' + value + '" type="text" readonly="readonly"/>'

                }
            }, {
                "orderable": false,
                "targets": [5],
                "render": function (data, type, row) {
                    var name = col_model.ws[3]
                    var value = row[name]

                    return '<input '
                             + ' data-id="' + row.ID
                        + '" data-model="ws" '
                        + ' data-name="' + name
                        + '" data-write="0" '
                        + ' value="' + value + '" type="text" readonly="readonly"/>'

                }
            }, {
                "orderable": false,
                "targets": [6],
                "render": function (data, type, row) {
                    var name = col_model.ws[4]
                    var value = getDate(row[name])
                    
                    return '<input '
                             +' data-id="' + row.ID
                        + '" data-model="ws" '
                        + ' data-name="' + name
                        + '" data-write="0" '
                        + ' value="' + value + '" type="text" readonly="readonly"/>'

                }
            },
            {
                "orderable": false,
                "targets": [7],
                "render": function (data, type, row) {
                    var name = col_model.ws[5]
                    var value = row[name]
                    return '<input '
                             +' data-id="' + row.ID
                        + '" data-model="ws" '
                        + ' data-name="' + name
                        + '" data-write="0" '
                        + ' value="' + value + '" type="text" readonly="readonly"/>'

                }
            }
            ],
            "drawCallback": function () {
                if ($('input[data-type="item"]').length == $('input[data-type="item"][checked="checked"]').length) {
                    $('#selectAll').parent().addClass('checked')
                } else {
                    $('#selectAll').parent().removeClass('checked')
                }
            },
            "footerCallback": function (row, data, start, end, display) {
            }
        })
    }


    var activeRow = function (model, dataId) {
        for (var i = 0; i < col_model[model].length; i++) {
            var selector = 'input[data-model="' + model + '"]'
                            + '[data-name="' + col_model[model][i] + '"]'
                            + '[data-id="' + dataId + '"]'
            $(selector).attr('data-write', col_model[model + "_write"][i])
            if (col_model[model + "_write"][i] === 1) {
                $(selector).removeAttr('readonly')
            }
        }
        $('a[data-model="' + model + '"][data-id="' + dataId + '"][op-type!="line"]').text('保存')
        if (dataId.indexOf('temp') > 0) $('a[data-model="' + model + '"][data-id="' + dataId + '"][op-type!="line"]').attr('op-type', "add")
        else $('a[data-model="' + model + '"][data-id="' + dataId + '"][op-type!="line"]').attr('op-type', "edit")
    }
    var deactiveRow = function (model, dataId, data) {
        console.log(data)
        for (var i = 0; i < col_model[model].length; i++) {
            var col_name = col_model[model][i]
            var selector = 'input[data-model="' + model + '"]'
                            + '[data-name="' + col_name + '"]'
                            + '[data-id="' + dataId + '"]'
            if (data[col_name] !== undefined) {
                $(selector).val(data[col_name])
            }

            if (col_name.indexOf('TIME') > 0) {
                $(selector).val(getDate(data[col_name]), col_name)
            }
            $(selector).attr('readonly', 'readonly')
        }
        $('a[data-model="' + model + '"][data-id="' + dataId + '"][op-type!="line"]').text('编辑')
        $('a[data-model="' + model + '"][data-id="' + dataId + '"][op-type!="line"]').attr('op-type', "active")
        $('a[data-model="' + model + '"][data-id="' + dataId + '"]').attr('data-id', data.ID)
        $('input[data-model="' + model + '"][data-id="' + dataId + '"]').attr('data-id', data.ID)
    }
    var selectAll = function (model) {
        select_model[model].ids = []
        select_model[model].temp_ids = []
        $('input[op-type="check"][data-model="' + model + '"]').each(function () {
            $(this).attr('checked', 'checked')
            if ($(this).attr('data-id').indexOf('temp') > 0) {
                select_model[model].temp_ids.push($(this).attr('data-id'))
            } else {
                select_model[model].ids.push($(this).attr('data-id'))
            }
        })
    }
    var deSelectAll = function (model) {
        select_model[model].ids = []
        select_model[model].temp_ids = []
        $('input[op-type="check"][data-model="' + model + '"]').each(function () {
            $(this).removeAttr('checked')
        })
    }


    var getDataModel = function (model, dataId) {
        
        var dataModel = {
            ID:0
        }
        if (dataId.indexOf('temp') < 0) {
            dataModel.ID = dataId
        }
        for (var i = 0; i < col_model[model].length; i++) {
            var col_name = col_model[model][i]
            var selector = 'input[data-model="' + model + '"]'
                            + '[data-name="' + col_name + '"]'
                            + '[data-id="' + dataId + '"]'
            dataModel[col_name] = $(selector).val()
        }
        return dataModel
    }
    var getDate = function (rawDate) {
        var dateTime = new Date(rawDate.substr(6, rawDate.length - 8) - 0)
        return dateTime.Format('yyyy-MM-dd hh:mm:ss')
    }


    var addLineRow = function () {
        if (current_workshop.WORKSHOP_CODE == '') {
            bootbox.alert({
                size: "small",
                animate: false,
                closeButton: false,
                className: "green-control",
                message: "请先保存车间"
            })
            return
        }
        settings.line_temp_id += 1
        var dataId = 'pl_temp_' + settings.line_temp_id
        var innerHtml = '<tr class="odd">'
       + '<td> <input data-model="pl" '
       + ' data-id="' + dataId + '" type="checkbox" op-type="check" class="checkbox"/> </td>'
       + '<td><a op-type="add" '
       + ' data-id="' + dataId + '" '
       + 'data-model="pl" class="btn btn-primary btn-xs green">保存</a></td>'
        for (var i = 0; i < col_model.pl.length; i++) {
            var name = col_model.pl[i]
            innerHtml += '<td><input '
                             + ' data-id="' + dataId
                        + '" data-model="pl" '
                        + ' data-name="' + name
                        + '" data-write="0" '
                        + ' value="" type="text" readonly="readonly"/></td>'
        }

        $('#line_grid tbody').prepend(innerHtml)
        activeRow('pl', dataId)

    }
    var editPL = function (dataId) {
        dataModel = getDataModel('pl', dataId)
        dataModel.WORKSHOP_NAME = current_workshop.WORKSHOP_NAME
        dataModel.WORKSHOP_CODE = current_workshop.WORKSHOP_CODE
        $.post('/Workshop/AddPipeline'
            , dataModel,
            function (data) {
                if (data.IsSuccess === true) {
                    deactiveRow('pl', dataId, data.Data[0])
                    $('#workshopSearchForm').submit()
                    initWorkShop()
                }
            })
    }
    var deletePL = function () {
        var model = 'pl'
        if (select_model.pl.ids.length === 0
            && select_model.pl.temp_ids.length === 0) {
            bootbox.alert({
                size: "small",
                animate: false,
                closeButton: false,
                className: "green-control",
                message: "未选中车间"
            }); return;
        }
        request = {
            IDS: select_model.pl.ids
        }
        $.post("/Workshop/DeletePipeline"
            , {
                rawrequest: JSON.stringify(request)
            }, function (data) {
                if (data.IsSuccess == true) {
                    for (var i = 0; i < select_model[model].ids.length; i++) {
                        $('input[op-type="check"][data-id="' + select_model[model].ids[i] + '"]').parent().parent().remove()
                    }
                    select_model[model].ids = []
                    initWorkShop()
                }
            }
            , 'json'
          )
        for (var i = 0; i < select_model[model].temp_ids.length; i++) {
            $('input[op-type="check"][data-id="' + select_model[model].temp_ids[i] + '"]').parent().parent().remove()
        }
        select_model[model].temp_ids = []
        $('#selectAllpl').removeAttr('checked')
        $('#selectAllpl').parent().removeClass('checked')
    }


    var editWs = function () {
        $.post('/Workshop/UpdateWorkshop'
            ,current_workshop,
            function (data) {
                if (data.IsSuccess === true) {
                    initeLineModel(data.Data[0])
                    initWorkShop()
                }
            })
    }
    var createWs = function () {
            $.post('/Workshop/AddWorkshop'
                    , current_workshop
                    ,
                    function (data) {

                        if (data.IsSuccess === true) {
                            initeLineModel(data.Data[0])
                            initWorkShop()
                        }
                    }
                    )
    }
    var enableWs = function (enabled) {
        var model = 'ws'
        if(select_model.ws.ids.length === 0 
            && select_model.ws.temp_ids.length === 0) {
            bootbox.alert({
                size: "small",
                animate: false,
                closeButton: false,
                className: "green-control",
                message: "未选中车间"
            }); return;
        }
        request = {
            IDS: select_model.ws.ids,
            WORKSHOP_STATUS:1
        }
        if (enabled !== true) {
            request.WORKSHOP_STATUS = 2
        }
        $.post("/Workshop/DeleteWorkshop"
            , {
                rawrequest:JSON.stringify(request)
            }, function (data) {
                if (data.IsSuccess == true) {                    
                    select_model[model].ids = []
                    initWorkShop()
                }
            }
            ,'json'
          )
        for (var i = 0; i < select_model[model].temp_ids.length; i++) {
            $('input[op-type="check"][data-id="' + select_model[model].temp_ids[i] + '"]').parent().parent().remove()
        }
        select_model[model].temp_ids = []
        $('#selectAllWs').removeAttr('checked')
        $('#selectAllWs').parent().removeClass('checked')
    }

    var initeLineModel = function (workshopData) {
        select_model = {
            ws: {
                ids: [],
                temp_ids: []
            },
            pl: {
                ids: [],
                temp_ids: []
            }
        }
        current_workshop = workshopData
        $('input[data-model="workshop"][data-name="WORKSHOP_NAME"]').val(current_workshop.WORKSHOP_NAME)
        $('input[data-model="workshop"][data-name="WORKSHOP_CODE"]').val(current_workshop.WORKSHOP_CODE)
        initLine()
       
    }

    
    var init = function () {
        initWorkShop()
        $('#addWorkshop').click(function () {
            initeLineModel({
                WORKSHOP_CODE: '',
                WORKSHOP_NAME:''
            })
            $('#pipLineModal').modal('show')
        })

        $('*[data-model="workshop"][op-type="save"]').click(function () {
            var workshop_name = $('input[data-model="workshop"][data-name="WORKSHOP_NAME"]').val()
            if (workshop_name == '') {
                bootbox.alert({
                    size: "small",
                    animate: false,
                    closeButton: false,
                    className: "green-control",
                    message: "车间名称不能为空"
                });return
            }
            if (current_workshop.WORKSHOP_CODE == '') {
                current_workshop.WORKSHOP_NAME = workshop_name
                createWs()
            } else {
                current_workshop.WORKSHOP_NAME = workshop_name
                editWs()
            }
        })
        $(document).on('click', 'a[op-type="line"]', function () {
            if ($(this).attr('data-id').indexOf("temp") > 0) {
                bootbox.alert({
                    size: "small",
                    animate: false,
                    closeButton: false,
                    className: "green-control",
                    message: "先保存车间"
                });
                return
            }
            initeLineModel(getDataModel('ws', $(this).attr('data-id')))
            $('#pipLineModal').modal('show')
        })




        $('#deleteWorkshop').click(function () { enableWs(false)})
        $('#activeWorkshop').click(function () { enableWs(true) })
        $('#selectAllWs').click(function () {
            var parent = $(this).parent()
            if (parent.hasClass('checked') === false) {
                selectAll('ws')
            } else {
                deSelectAll('ws')
            }
        })
        $('#refreshWorkshop').click(function () {
            $('#workshopSearchForm').submit()
        })

        $(document).on('click', 'input[op-type="check"]', function () {
            var model = $(this).attr('data-model')
           
            if ($(this).attr('checked') == 'checked') {
                if ($(this).attr('data-id').indexOf('temp') > 0) {
                    select_model[model].temp_ids.push($(this).attr('data-id'))
                } else {
                    select_model[model].ids.push($(this).attr('data-id'))
                }
            } else {
                if ($(this).attr('data-id').indexOf('temp') > 0) {
                    select_model[model].temp_ids.removeElement($(this).attr('data-id'))
                } else {
                    select_model[model].ids.removeElement($(this).attr('data-id'))
                }
            }
        })
        $(document).on('click', 'a[op-type="add"][data-model="pl"]', function () {
            var dataId = $(this).attr('data-id')
            var model = $(this).attr('data-model')
            editPL(dataId)
        })
        $(document).on('click', 'a[op-type="edit"][data-model="pl"]', function () {
            var dataId = $(this).attr('data-id')
            var model = $(this).attr('data-model')
            editPL(dataId)
        })
        $(document).on('click', 'a[op-type="active"][data-model="pl"]', function () {
            var dataId = $(this).attr('data-id')
            var model = $(this).attr('data-model')
            activeRow('pl', dataId)
        })
        $('#addLine').click(addLineRow)
        $('#deleteLine').click(deletePL)


        $('#selectAllpl').click(function () {
            var parent = $(this).parent()
            if (parent.hasClass('checked') === false) {
        
                selectAll('pl')
            } else {
                deSelectAll('pl')
            }
        })
        $('#refreshLine').click(function () {
            $('#lineSearchForm').submit()
        })

    }
    return {
        settings: settings,
        init:init
    }
})(jQuery)
$(document).ready(function () {
    MB.page.workshop.init()
})
